﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Net;
using System.Threading;
using Microsoft.WindowsAzure;
using Microsoft.WindowsAzure.Diagnostics;
using Microsoft.WindowsAzure.ServiceRuntime;
using Microsoft.WindowsAzure.StorageClient;

namespace Hangout.Cloud.Agent.Agents
{
    class QueueReader 
    {

        public void Run()
        {
            // This is a sample worker implementation. Replace with your logic.
            // initialize the account information

            Web.Model.HangoutDBEntities context = new Web.Model.HangoutDBEntities();
            try
            {
                CloudStorageAccount.SetConfigurationSettingPublisher((configName, configSetter) =>
                {
                    configSetter(RoleEnvironment.GetConfigurationSettingValue(configName)); // Error and error message is "error"

                    RoleEnvironment.Changed += (sender, arg) =>
                    {
                        if (arg.Changes.OfType<RoleEnvironmentConfigurationSettingChange>()
                          .Any((change) => (change.ConfigurationSettingName == configName)))
                        {
                            if (!configSetter(RoleEnvironment.GetConfigurationSettingValue(configName)))
                            {
                                RoleEnvironment.RequestRecycle();
                            }
                        }
                    };
                });


            }
            catch (System.Exception ex)
            {
                Web.Core.Exceptions.ExceptionReporting.AddAnException(0, Web.Core.ClientType.WindowsAzure, ex, ref context);

            }


                var storageAccount = CloudStorageAccount.FromConfigurationSetting("StorageConnectionString");

                // retrieve a reference to the messages queue
                var queueClient = storageAccount.CreateCloudQueueClient();
                var queue = queueClient.GetQueueReference("wassupqueue");
           

                

                while (true)
                {
                    try
                    {
                        Trace.WriteLine("QR ENTERED");
                       

                        if (queue.Exists())
                        {
                            var msg = queue.GetMessage();

                            if (msg != null)
                            {

                                context = new Web.Model.HangoutDBEntities();

                                string text = msg.AsString;

                                if (text.Contains("RefreshLikes"))
                                {
                                    int userId = Convert.ToInt32(text.Split(':')[1]);
                                    Web.Core.Tokens.FacebookTokens.RefreshTokens(userId, ref context);

                                }

                                if (text.Contains("Compatibility"))
                                {
                                    int userId = Convert.ToInt32(text.Split(':')[1]);
                                    Agents.CompatibilityAgent.UpdateCompatibility(userId, ref context); //update compatibility
                                }

                                if (text.Contains("Trophy"))
                                {
                                    int userId = Convert.ToInt32(text.Split(':')[1]);
                                    Core.Trophy.UpdateTrophies(userId, ref context);
                                }

                                if (text.Contains("HangoutAdded"))
                                {
                                    int hangoutid = Convert.ToInt32(text.Split(':')[1]);
                                    int userId = Convert.ToInt32(text.Split(':')[3]);
                                    Core.Meetup.HagnoutAdded(hangoutid, userId);
                                }
                                

                                queue.DeleteMessage(msg);
                            }
                            else
                            {
                                context = null;
                                Thread.Sleep(new TimeSpan(0, 0, 30)); //start after 30 seconds :)
                            }
                        }
                        else
                        {
                            context = null;
                            Thread.Sleep(new TimeSpan(0, 0, 30)); //start after 30 seconds :)
                        }
                    }
                    catch(Exception ex)
                    {
                        Web.Core.Exceptions.ExceptionReporting.AddAnException(0,Web.Core.ClientType.WindowsAzure,ex,ref context);
                    }

                }

            }
           
        }


    }

